<?php
namespace app\controller;

use app\BaseController;
use think\validate\ValidateRule;
use think\facade\Db;
use think\facade\Session;
use app\model\Brands as BrModel;
use app\model\User as UserModel;

class User extends BaseController
{
    protected $middleware = [
        // 对所有方法有效
        '\app\middleware\NavCheck',
        '\app\middleware\UrlCheck',
        '\app\middleware\LoginCheck',
    ];

    public function index(){
        return view();
    }

    public function data($limit,$page){
        $offset = ($page-1)*$limit;
        $list = UserModel::limit($offset,$limit)->select();
        $count = UserModel::count();
        return json(["code"=>0,"msg"=>"查询成功","count"=>$count,"data"=>$list]);
    }

    public function add(){
        if($this->request->isPost()){
            $data = $this->request->post();
            var_dump($data);
            $data['user_pwd']=md5($data['user_pwd']);
            $user = new UserModel();
            $res = $user->save($data);

            if($res){
                $this->success("添加成功","index");
            }
            $this->error("添加失败");
        }
        return view();
    }

    public function update(){
        if($this->request->isPost()){
            $data = $this->request->post();

            $res = Db::name('user')->save($data);
            if($res){
                $this->success("修改成功","index");
            }
            $this->error("修改失败");
        }

        $id = $this->request->param('id');
        $goods = UserModel::where("id",$id)->find();
        return view("add",["goods"=>$goods]);
    }

    public function del(){
        $id = $this->request->post('id');
        $res = Db::name('user')->where('id',$id)->delete();

        if($res){
            return json(["code"=>0,"msg"=>"删除成功"]);
        }
        return json(["code"=>400,"msg"=>"删除失败"]);
    }
}
